package com.longcheng.sensordemo;

import android.content.Context;
import android.hardware.Sensor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LongWH on 2016/11/14.
 * All Rights Reserved by ZhiYou @2016 - 2017
 */
public class SensorAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
//    private List<Sensor> mList ;
    private List<Sensor> mList = new ArrayList<>();
    /**
     * @param context
     * @param list
     */
    public SensorAdapter(Context context,List<Sensor> list) {
        if (list != null) {
//            mList = list;
            mList.addAll(list);
        }
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Sensor getItem(int position) {
        if (position >= 0 && position < getCount()) {
            return mList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView != null) {
            holder= (ViewHolder) convertView.getTag();
        } else {
            convertView = mInflater.inflate(R.layout.list_item, parent,false);
            holder = new ViewHolder(convertView);
            holder.mName = (TextView) convertView.findViewById(R.id.list_item_name);
            holder.mType = (TextView) convertView.findViewById(R.id.list_item_type);
            holder.mVersion = (TextView) convertView.findViewById(R.id.list_item_version);
        }
        Sensor s = getItem(position);
        holder.mName.setText(s.getName());
        holder.mType.setText(
                String.format("%s%s","type: ",s.getType()));
        holder.mVersion.setText(String.format("%s%s","版本号:", s.getVersion()));

        return convertView;
    }

    private static class ViewHolder {
        private TextView mName;
        private TextView mType;
        private TextView mVersion;

        public ViewHolder(View convertView) {
            if (convertView != null) {
               // convertView.getTag();
                convertView.setTag(this);
                // TODO: 2016/11/14
            }
        }
    }

    public void upData(List<Sensor> data){
        mList.clear();
        if(data != null){
            mList.addAll(data);
        }
        notifyDataSetChanged();
    }


}
